<?php

load_files(
  KVF_INCLUDES."/lib/user.class.php"
);

class ApplicationModule extends KvfModule
{
  public $SETTINGS = array();
  protected static $_USER = null;
  protected $_RequiresAccess = ACCESS::noauth;

  protected function BeforeFilters()
  {
    parent::BeforeFilters();
    $this->LoadSettings();
    $this->LoadOverrides();
    $this->CheckLogin();

    $this->ValidateAccess($this->_RequiresAccess);
  }

  public function UserLoggedIn()
  {
    return !is_null(self::$_USER);
  }

  protected function AfterFilters()
  {
    parent::AfterFilters();
    self::$_LayoutParams["_USERDATA"] = self::$_USER;
  }

  public function __get($n)
  {
    if($n == "USER")
    {
      return self::$_USER;
    }
    else
    {
      return null;
    }
  }

  public function __set($n,$v)
  {
    return null;
  }

  protected function CheckLogin()
  {
    if(!array_key_exists(CONFIG::COOKIENAME, self::$COOKIES))
    {
      return false;
    }

    if(!self::$COOKIES[CONFIG::COOKIENAME])
    {
      return false;
    }

    // check to see if user has an active session using the session string found in cookie
    $q  = self::$DB->FindQuery(array('sessions as s', 'users as u' => "s.user_id = u.user_id"));
    $q->fields = array('s.session_id','s.started','s.lastact','s.useragent','s.ipaddr','u.*');
    $q->conditions = "s.session_id = ?";
    $q->limit = "1";
    $q->parameters = array(self::$COOKIES[CONFIG::COOKIENAME]);

    $res = self::$DB->Process($q);

    if(!$res || !$res->user_id)
    {
      setcookie(CONFIG::COOKIENAME, "", time() - 3000, CONFIG::BASEURI);
      return false;
    }

    // update the last page view time
    $q = self::$DB->UpdateQuery('sessions');
    $q->conditions = "session_id = ?";
    $q->parameters = array(self::$COOKIES[CONFIG::COOKIENAME]);
    $q->limit = "1";
    $q->fields = array('lastact' => time());

    self::$DB->Process($q);

    self::$_USER = new User($res);

    return true;
  }

  public function DestroySession($id)
  {
    $q = self::$DB->DeleteQuery('sessions');
    $q->conditions = "session_id = ?";
    $q->parameters = array($id);
    $q->limit = "1";

    return self::$DB->Process($q);
  }

  public function LoadSettings()
  {
    $keys = array_keys(SETTINGS::$VARS);
    $in = "";
    $m = count($keys);
    for($i = 0; $i < $m; $i++)
    {
      $in .= "?, ";
    }

    $in = substr($in,0,-2);

    $q = self::$DB->FindQuery('settings');
    $q->conditions = "setting_id IN (".$in.")";
    $q->parameters = $keys;

    $res = self::$DB->Process($q);

    foreach($res as $set)
    {
      $this->SETTINGS[$set->setting_id] = unserialize(urldecode($set->setting_value));
      unset($keys[array_search($set->setting_id, $keys)]);
    }

    foreach($keys as $key)
    {
      $this->SETTINGS[$key] = SETTINGS::$VARS[$key][1];
    }
  }

  public function LoadOverrides()
  {
    $keys = array_keys(SETTINGS::$VARS_OVERRIDES);
    $in = "";
    $m = count($keys);
    for($i = 0; $i < $m; $i++)
    {
      $in .= "?, ";
    }

    $in = substr($in,0,-2);

    $q = self::$DB->FindQuery('settings');
    $q->conditions = "setting_id IN (".$in.")";
    $q->parameters = $keys;

    $res = self::$DB->Process($q);

    foreach($res as $set)
    {
      $this->SETTINGS[$set->setting_id] = unserialize(urldecode($set->setting_value));
      unset($keys[array_search($set->setting_id, $keys)]);
    }

    foreach($keys as $key)
    {
      $this->SETTINGS[$key] = SETTINGS::$VARS_OVERRIDES[$key][1];
    }
  }

  public function ValidateAccess($access_level, $justtf = false)
  {
    if($access_level == 0)
    {
      return true;
    }
    elseif(!is_null(self::$_USER) && self::$_USER->HasPrivilegeFor($access_level))
    {
      return true;
    }
    elseif(!is_null(self::$_USER))
    {
      //Goto Access Denied
      if($justtf)
      {
        return false;
      }
      else
      {
        self::Error("Access Denied.");
        DoRedirect(self::$ROUTER->UrlFor("page","index",array(),array(), false));
      }
    }
    else
    {
      //Goto Login
      if($justtf)
      {
        return false;
      }
      else
      {
        DoRedirect(self::$ROUTER->UrlFor("user","login",array(),array(), false));
      }
    }
  }

}

?>
